﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;

namespace CompactFileAndFolders
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateFilesAndDirectiries();

            // zip

            ZipOutputStream zipOutStream = new ZipOutputStream(File.Create("my.zip"));
            CreateFileZipEntry(zipOutStream, "file1.txt", "file1.txt");
            CreateFileZipEntry(zipOutStream, @"folder1\folder2\folder3\file2.txt", "file2.txt");
            zipOutStream.Close();

            // unzip

            Directory.CreateDirectory("ZipOutPut");
            ZipInputStream zipInputStream = new ZipInputStream(File.Open("my.zip", FileMode.Open));
            ZipEntry zipEntryFromZippedFile = zipInputStream.GetNextEntry();
            while (zipEntryFromZippedFile != null)
            {
                if (zipEntryFromZippedFile.IsFile)
                {
                    FileInfo fInfo = new FileInfo(string.Format("ZipOutPut\\{0}", zipEntryFromZippedFile.Name));
                    if (!fInfo.Directory.Exists) fInfo.Directory.Create();

                    FileStream file = fInfo.Create();
                    byte[] bufferFromZip = new byte[zipInputStream.Length];
                    zipInputStream.Read(bufferFromZip, 0, bufferFromZip.Length);
                    file.Write(bufferFromZip, 0, bufferFromZip.Length);
                    file.Close();
                }
                zipEntryFromZippedFile = zipInputStream.GetNextEntry();
            }
            zipInputStream.Close();

        }
        private static void CreateFileZipEntry(ZipOutputStream zipOutStream, string name, string filePath)
        {
            ZipEntry fileZipEntry = new ZipEntry(name);
            zipOutStream.PutNextEntry(fileZipEntry);
            FileStream fileStram = File.Open(filePath, FileMode.Open);
            byte[] buffer = new byte[fileStram.Length];
            fileStram.Read(buffer, 0, buffer.Length);
            zipOutStream.Write(buffer, 0, buffer.Length);
            zipOutStream.CloseEntry();
        }
        private static void CreateFilesAndDirectiries()
        {
            List<FileStream> files = new List<FileStream>();
            files.Add(File.Create("file1.txt"));
            files.Add(File.Create("file2.txt"));
            files.ForEach(FillHelloWorldInStream);
            files.ForEach(fStream => fStream.Close());
        }

        private static void FillHelloWorldInStream(FileStream file)
        {
            byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
            file.Write(buffer, 0, buffer.Length);
        }
    }
}
